package cn.hzking.gjmall.activitys.second;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mikhaellopez.circularimageview.CircularImageView;
import com.tencent.smtt.sdk.WebView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.MainActivity;
import cn.hzking.gjmall.adpters.gooddetail.GoodDetailPopAdapter;
import cn.hzking.gjmall.app.Gjmall;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.GoodDetailBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.utils.IconTextSpanUtils;
import cn.hzking.gjmall.utils.OnClickEvent;
import cn.hzking.gjmall.utils.PriceFormatUtils;
import cn.hzking.gjmall.utils.helpers.GoodDetailConvenientBannerHelper;
import cn.hzking.gjmall.view.MyListView;
import cn.hzking.gjmall.view.SimpleOptionView;
import cn.hzking.gjmall.view.convenientbanner.ConvenientBanner;
import cn.hzking.gjmall.view.countdown.RushBuyCountDownTimerView;
import cn.hzking.gjmall.view.countdown.TimeState;

public class GoodDetailActivity extends ColorStatuBarActivity {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;//头部的toolbar
    @Bind(R.id.gooddetail_gohome)
    LinearLayout gooddetailGohome;//返回主页按钮
    @Bind(R.id.gooddetail_share)
    LinearLayout gooddetailShare; //分享按钮
    @Bind(R.id.gooddetail_gocar)
    RelativeLayout gooddetailGocar;//前往购物车按钮
    @Bind(R.id.unread_num)
    TextView unreadNum; //购物车数量
    @Bind(R.id.home_banner)
    ConvenientBanner homeBanner;//商品详情轮播图
    @Bind(R.id.gooddetail_title)
    TextView gooddetailTitle; //商品标题
    @Bind(R.id.gooddetail_newprice)
    TextView gooddetailNewprice; //商品新价格
    @Bind(R.id.gooddetail_oldprice)
    TextView gooddetailOldprice; //商品老价格
    @Bind(R.id.gooddetail_zhenqian)
    TextView gooddetailZhenqian; //卖出商品挣的钱
    @Bind(R.id.gooddetail_suilv)
    TextView gooddetailSuilv; //这一件商品所需要交的税
    @Bind(R.id.gooddetail_soucanImage)
    ImageView gooddetailSoucanImage; //收藏的图标 isFavorite -1 没收藏 ,0 已收藏
    @Bind(R.id.gooddetail_text1)
    TextView gooddetailText1; //商家提醒话语 describe字段
    @Bind(R.id.gooddetail_text2)
    TextView gooddetailText2;//是否免运费提示 issuingBay == 1满98元包基础运费，超重超地区运费另计 ,   issuingBay == 0 该商品免运费
    @Bind(R.id.gooddetail_text3)
    TextView gooddetailText3; //该商品支持七天无理由退货 "nonRefunded"  //  true该商品支持七天无理由退换货政策,false 该商品不支持七天无理由退换货政策
    @Bind(R.id.good_list_shuoming_ll)
    LinearLayout goodListShuomingLl; //说明布局
    @Bind(R.id.home_bar_headimage)
    CircularImageView homeBarHeadimage;//店主头像
    @Bind(R.id.gooddetail_shopname)
    TextView gooddetailShopname;  //小店名称
    @Bind(R.id.gooddetail_shopdetaitext)
    TextView gooddetailShopdetaitext; //小店个性签名
    @Bind(R.id.gooddetail_shopdetail)
    LinearLayout gooddetailShopdetail; //店铺信息
    @Bind(R.id.gooddetail_goodliangdian_string)
    TextView gooddetailGoodliangdianString; //产品亮点
    @Bind(R.id.gooddetail_goodliangdian)
    LinearLayout gooddetailGoodliangdian;//产品亮点布局
    @Bind(R.id.goodlist_webview)
    WebView goodlistWebview; //webview
    @Bind(R.id.gooddetail_state)
    TextView textState; //商品的状态
    @Bind(R.id.gooddetailnomalbuttom_addcar)
    TextView gooddetailnomalbuttomAddcar; //普通的加入购物车
    @Bind(R.id.gooddetailnomalbuttom_buy)
    TextView gooddetailnomalbuttomBuy;//普通的立即购买
    @Bind(R.id.gooddetailnomalbuttom)
    LinearLayout gooddetailnomalbuttom; //普通的底部
    @Bind(R.id.gooddetailohterbuttom_buy)
    TextView gooddetailohterbuttomBuy; //特殊的立即购买
    @Bind(R.id.gooddetailohterbuttom)
    LinearLayout gooddetailOtherButtom;//特殊的底部
    @Bind(R.id.gooddetail_cuttime)
    RushBuyCountDownTimerView gooddetailCutTime;//倒计时
    @Bind(R.id.gooddetail_activity_price)
    TextView activityPriceText;//活动价格
    @Bind(R.id.gooddetail_soucan_ll)
    LinearLayout soucanLL;
    private String itemId;
    int num = 1;//popupwindow中商品数量
    int carGoodNum = 1;//加入购物车的商品数量
    /*------------贝塞尔曲线---------*/
    @Bind(R.id.gooddetail_car)
    ImageView imageCar;
    @Bind(R.id.gooddetail_rl)
    RelativeLayout gooddetailRl;
    private PathMeasure mPathMeasure;
    /**
     * 贝塞尔曲线中间过程的点的坐标
     */
    private float[] mCurrentPosition = new float[2];
    private String imageUrl;//加入购物车图片的地址
    private Bitmap bitmap;
    private int carNum = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_good_detail);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        simpleTileView.setTitle("商品详情");
        Intent intent = getIntent();
        itemId = intent.getStringExtra("itemId");
        getNetData(this, true, true);
    }


    private void getNetData(Activity activity, boolean isShow, boolean isCancel) {
        RetrofitFactory.getInstant().API()
                .getGoodDetailData(itemId)
                .compose(this.<GoodDetailBean>setThread())
                .subscribe(new BaseObserver<GoodDetailBean>(activity, isShow, isCancel) {
                    @Override
                    protected void onSuccees(GoodDetailBean goodDetailBean) throws Exception {
                        GoodDetailBean.DataBean data = goodDetailBean.getData();
                        boolean list = data.isList();//true表示正在上架,false表示已经下架
                        boolean soldOut = data.isSoldOut();//true表示已经售罄,false表示没有售罄
                        boolean whetherSnapup = data.isWhetherSnapup();//true表示是活动,false表示不是活动
                        boolean whetherVirtual = data.isWhetherVirtual();//true表示是虚拟商品,false表示不是虚拟商品
                        imageUrl = data.getImageUrl();
                        if (!whetherVirtual) {//正常商品详情
                            if (list && !soldOut && !whetherSnapup) {//正常商品的正常逻辑
                                showNomalContent(goodDetailBean);
                            } else if (!list) {//正常商品下架了
                                showDownListContent(goodDetailBean);
                            } else if (soldOut) {//正常商品售罄
                                showSoutOutContent(goodDetailBean);
                            } else if (whetherSnapup) {//正常商品活动(抢购)
                                showActiivtyContent(goodDetailBean);
                            }
                        } else {//虚拟商品
                            if (list && !soldOut && !whetherSnapup) {//虚拟商品的正常逻辑
                                showVirtualContent(goodDetailBean);
                            } else if (!list) {//虚拟商品下架了
                                showVirtualDownCutContent(goodDetailBean);
                            } else if (soldOut) {//虚拟商品售罄
                                showVirtualsoutoutContent(goodDetailBean);
                            } else if (whetherSnapup) {//虚拟商品活动(抢购)
                                showVirtualActivityuContent(goodDetailBean);
                            }
                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

/*-----------------------------------正常商品业务逻辑------------------------------------------------*/

    //正常商品显示最基本的商品详情内容
    private void showNomalContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //标题
        showGoodTitle(data);
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        //商家提示语
        showShopMarkedWords(data);
        //包邮信息
        showPostage(data);
        //是否七天包退
        showRefunded(data);
        //是否有商品亮点介绍
        showGoodStart(data);
        //加载html片段
        showHtml(data);
        //绑定事件
        initListener();
        gooddetailnomalbuttomBuy.setOnClickListener(listener);//正常情况下立即购买
        gooddetailnomalbuttomAddcar.setOnClickListener(listener);//正常情况下加入购物车
        gooddetailShare.setTag(goodDetailBean);
        gooddetailnomalbuttomAddcar.setTag(goodDetailBean);
        gooddetailnomalbuttomBuy.setTag(goodDetailBean);

    }

    //正常商品下架的商品详情内容
    private void showDownListContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //标题
        showGoodTitle(data);
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        goodListShuomingLl.setVisibility(View.GONE);//商家说明布局隐藏
        gooddetailShopdetail.setVisibility(View.GONE);//店铺信息布局隐藏
        gooddetailGoodliangdian.setVisibility(View.GONE);//产品亮点布局隐藏
        goodlistWebview.setVisibility(View.GONE);//webview隐藏
        textState.setText("商品已下架");
        //初始化监听事件
        initListener();
        gooddetailnomalbuttomAddcar.setEnabled(false);
        gooddetailnomalbuttomBuy.setEnabled(false);

    }

    //正常商品售罄的商品详情内容
    private void showSoutOutContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //标题
        showGoodTitle(data);
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        //商家提示语
        showShopMarkedWords(data);
        //包邮信息
        showPostage(data);
        //是否七天包退
        showRefunded(data);
        //是否有商品亮点介绍
        showGoodStart(data);
        //加载html片段
        showHtml(data);
        textState.setVisibility(View.VISIBLE);
        textState.setText("商品已售罄");
        //初始化监听事件
        initListener();
        gooddetailnomalbuttomAddcar.setEnabled(false);
        gooddetailnomalbuttomBuy.setEnabled(false);

    }

    //正常商品活动的商品详情内容
    private void showActiivtyContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //倒计时
        showMGoodCutTime(data);
        //标题
        showGoodTitle(data);
        activityPriceText.setVisibility(View.VISIBLE);
        activityPriceText.setText(String.format(Locale.CHINA, "抢购价格¥ %s", data.getSnapupPrice()));//活动价格
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        //商家提示语
        showShopMarkedWords(data);
        //包邮信息
        showPostage(data);
        //是否七天包退
        showRefunded(data);
        //是否有商品亮点介绍
        showGoodStart(data);
        //加载html片段
        showHtml(data);
        gooddetailnomalbuttomAddcar.setEnabled(true);
        gooddetailnomalbuttomBuy.setEnabled(true);
        //初始化监听事件
        initListener();
        gooddetailnomalbuttomAddcar.setOnClickListener(listener);
        gooddetailnomalbuttomBuy.setOnClickListener(listener);
        gooddetailnomalbuttomAddcar.setTag(goodDetailBean);
        gooddetailnomalbuttomBuy.setTag(goodDetailBean);

    }


/*---------------------------------------虚拟商品业务逻辑----------------------------------------------*/

    //虚拟商品商品显示最基本的商品详情内容
    private void showVirtualContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //标题
        showGoodTitle(data);
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        //商家提示语
        showShopMarkedWords(data);
        //包邮信息
        showPostage(data);
        //是否七天包退
        showRefunded(data);
        goodListShuomingLl.setVisibility(View.VISIBLE);//商家说明布局隐藏
        gooddetailGoodliangdian.setVisibility(View.GONE);//产品亮点布局隐藏
        goodlistWebview.setVisibility(View.GONE);//webview隐藏
        gooddetailnomalbuttom.setVisibility(View.GONE);
        gooddetailOtherButtom.setVisibility(View.VISIBLE);
        //初始化监听事件
        initListener();
        gooddetailohterbuttomBuy.setOnClickListener(listener);//虚拟商品情况下立即购买
        gooddetailShare.setTag(goodDetailBean);
        gooddetailohterbuttomBuy.setTag(goodDetailBean);


    }


    //虚拟商品下架的商品详情内容
    private void showVirtualDownCutContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //标题
        showGoodTitle(data);
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        //商家提示语
        showShopMarkedWords(data);
        //包邮信息
        if (data.getIssuingBay() == 1) {//不免运费
            gooddetailText2.setText("");

        } else {
            gooddetailText2.setText("");
        }
        //是否七天包退
        showRefunded(data);
        goodListShuomingLl.setVisibility(View.GONE);//商家说明布局隐藏
        gooddetailGoodliangdian.setVisibility(View.GONE);//产品亮点布局隐藏
        goodlistWebview.setVisibility(View.GONE);//webview隐藏
        gooddetailnomalbuttom.setVisibility(View.GONE);
        gooddetailOtherButtom.setVisibility(View.VISIBLE);
        gooddetailohterbuttomBuy.setEnabled(false);//立即购买按钮不能点击
        textState.setVisibility(View.VISIBLE);
        textState.setText("商品已下架");
        //初始化监听事件
        initListener();
        gooddetailohterbuttomBuy.setOnClickListener(listener);//正常情况下立即购买

    }

    //虚拟商品售罄的商品详情内容
    private void showVirtualsoutoutContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //标题
        showGoodTitle(data);
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        //商家提示语
        showShopMarkedWords(data);
        //包邮信息
        showPostage(data);
        //是否七天包退
        showRefunded(data);
        goodListShuomingLl.setVisibility(View.GONE);//商家说明布局隐藏
        gooddetailGoodliangdian.setVisibility(View.GONE);//产品亮点布局隐藏
        goodlistWebview.setVisibility(View.GONE);//webview隐藏
        gooddetailnomalbuttom.setVisibility(View.GONE);
        gooddetailOtherButtom.setVisibility(View.VISIBLE);
        gooddetailohterbuttomBuy.setEnabled(false);//立即购买按钮不能点击
        textState.setVisibility(View.VISIBLE);
        textState.setText("商品已售罄");
        //初始化监听事件
        initListener();
        gooddetailohterbuttomBuy.setOnClickListener(listener);//正常情况下立即购买

    }


    //虚拟商品抢购的商品详情内容
    private void showVirtualActivityuContent(GoodDetailBean goodDetailBean) {
        GoodDetailBean.DataBean data = goodDetailBean.getData();
        //轮播图
        showBanner(data);
        //倒计时
        showVGoodCutTime(data);
        //标题
        showGoodTitle(data);
        //新价格
        gooddetailNewprice.setText("¥ " + data.getPrice());
        //旧价格
        gooddetailOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        gooddetailOldprice.setText("¥ " + data.getAvecostPrice());
        //活动价格
        activityPriceText.setVisibility(View.VISIBLE);
        activityPriceText.setText(String.format(Locale.CHINA, "抢购价格¥ %s", data.getSnapupPrice()));//活动价格
        //赚的钱(不是商家,没有这个字段)
        showMakeMoney(data);
        //跨境税率
        showSuiLv(data);
        //是否收藏
        showCollect(data);
        //商家提示语
        showShopMarkedWords(data);
        //包邮信息
        showPostage(data);
        //是否七天包退
        showRefunded(data);
        goodListShuomingLl.setVisibility(View.GONE);//商家说明布局隐藏
        gooddetailGoodliangdian.setVisibility(View.GONE);//产品亮点布局隐藏
        goodlistWebview.setVisibility(View.GONE);//webview隐藏
        gooddetailnomalbuttom.setVisibility(View.GONE);
        gooddetailOtherButtom.setVisibility(View.VISIBLE);
        //初始化监听事件
        initListener();
        gooddetailohterbuttomBuy.setOnClickListener(listener);//虚拟商品情况下立即购买
        gooddetailShare.setTag(goodDetailBean);
        gooddetailohterbuttomBuy.setTag(goodDetailBean);

    }

    /*---------------------------------------监听事件----------------------------------------------*/
    OnClickEvent listener = new OnClickEvent() {
        @Override
        public void singleClick(View v) {
            switch (v.getId()) {
                case R.id.gooddetail_soucanImage://收藏
                    boolean isCollect = (boolean) v.getTag();
                    if (isCollect) {//如果已经收藏,点击取消收藏
                        // todo 进行取消收藏操作
                        gooddetailSoucanImage.setSelected(false);

                    } else {//如果没有收藏,点击进行收藏
                        // todo 进行收藏操作
                        gooddetailSoucanImage.setSelected(true);
                    }

                    break;
                case R.id.gooddetail_gohome://前往主页
                    EventBus.getDefault().post("goHome");
                    Intent intent = new Intent(GoodDetailActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                case R.id.gooddetail_share://分享
                    //todo 分享功能
                    break;
                case R.id.gooddetail_gocar://前往购物车
                    EventBus.getDefault().post("goCar");
                    Intent intent1 = new Intent(GoodDetailActivity.this, MainActivity.class);
                    startActivity(intent1);
                    break;
                case R.id.gooddetailnomalbuttom_addcar://普通的加入购物车
                    GoodDetailBean goodDetailBean2 = (GoodDetailBean) v.getTag();
                    showPop(goodDetailBean2, false);

                    break;
                case R.id.gooddetailnomalbuttom_buy://普通的立即购买
                    GoodDetailBean goodDetailBean = (GoodDetailBean) v.getTag();
                    showPop(goodDetailBean, true);
                    break;
                case R.id.gooddetailohterbuttom_buy://特殊的立即购买(虚拟商品)
                    GoodDetailBean goodDetailBean1 = (GoodDetailBean) v.getTag();
                    showPop(goodDetailBean1, true);
                    break;
            }
        }
    };

    /*---------------------------------------购买和加入购物车的popupwindow---------------------------------------------*/
    //popupwindow
    private void showPop(GoodDetailBean goodDetailBean, final boolean isToBuy) {
        final List<GoodDetailBean.DataBean.SkusBean> skus = goodDetailBean.getData().getSkus();
        View popView = View.inflate(this, R.layout.pop_gooddetail, null);
        MyListView myListView = popView.findViewById(R.id.pop_gooddetail_rv);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        myListView.setLayoutManager(gridLayoutManager);
        final GoodDetailPopAdapter goodDetailPopAdapter = new GoodDetailPopAdapter(R.layout.item_gooddetail_pop, skus);
        myListView.setAdapter(goodDetailPopAdapter);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int length = skus.get(position).getSkuname().length();
                if (length <= 4) {
                    return 1;
                } else if (length <= 8) {
                    return 2;
                } else if (length <= 12) {
                    return 3;
                }
                return 1;
            }
        });

        final CircularImageView imageHead = popView.findViewById(R.id.home_bar_headimage);
        final TextView newPriceText = popView.findViewById(R.id.pop_gooddetail_newprice);
        final TextView olderPriceText = popView.findViewById(R.id.pop_gooddetail_oldprice);
        TextView cutText = popView.findViewById(R.id.pop_cut);
        final TextView numText = popView.findViewById(R.id.pop_numtext);
        TextView addText = popView.findViewById(R.id.pop_add);
        ImageView cancelImage = popView.findViewById(R.id.pop_dismiss);
        TextView sureText = popView.findViewById(R.id.pop_gooddetail_sure);

        numText.setText(String.valueOf(num));

        if (skus.size() == 1) {//只有一条sku,第一次进入显示sku内容
            popOtherOneItem(0, skus, imageHead, newPriceText, olderPriceText);

        } else if (skus.size() > 1) {//有多条sku,第一次进入显示spu内容
            GoodDetailBean.DataBean popData = goodDetailBean.getData();
            String imageUrl = popData.getImageUrl();
            JSONArray imageList = JSON.parseArray(imageUrl);
            String imageUri = (String) imageList.get(0);
            Glide.with(this).load(Gjmall.getOssHost() + imageUri).into(imageHead);
            newPriceText.setText(String.format(Locale.CHINA, "¥ %s", String.valueOf(popData.getPrice())));
            olderPriceText.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
            olderPriceText.setText(String.format(Locale.CHINA, "¥ %s", String.valueOf(popData.getAvecostPrice())));
        }

        int width = getResources().getDisplayMetrics().widthPixels;
        final PopupWindow popWindow = new PopupWindow(popView, width, RelativeLayout.LayoutParams.WRAP_CONTENT);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置同意在外点击消失
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //条目点击事件
        goodDetailPopAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<GoodDetailBean.DataBean.SkusBean> data = goodDetailPopAdapter.getData();
                int size = data.size();
                if (size > 0) {//有多个sku
                    if (data.get(position).isWhetherActivite()) {//如果是活动
                        popItemChecked(position, data, size,goodDetailPopAdapter, imageHead, newPriceText, olderPriceText);

                    } else {//如果不是活动
                        if (data.get(position).getCurrentNumber() > 0) {//不是活动,并且有库存
                            for (int i = 0; i < size; i++) {
                                skus.get(i).setSelected(false);
                            }
                            data.get(position).setSelected(true);
                            goodDetailPopAdapter.notifyDataSetChanged();
                            popOtherOneItem(position, skus, imageHead, newPriceText, olderPriceText);
                        }
                    }


                }

            }
        });
        //减号点击事件
        cutText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isToBuy) {//立即购买
                    if (num > 0) {
                        num--;
                        numText.setText(String.valueOf(num));
                    }
                } else {//加入购物车
                    carGoodNum--;
                    numText.setText(String.valueOf(carGoodNum));
                }

            }
        });
        //加号点击事件
        addText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isToBuy) {//立即购买
                    num++;
                    numText.setText(String.valueOf(num));
                } else {//加入购物车
                    carGoodNum++;
                    numText.setText(String.valueOf(carGoodNum));
                }
            }
        });

        //取消按钮
        cancelImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = 1;
                carGoodNum = 1;
                popWindow.dismiss();
            }
        });
        //确定按钮
        sureText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isToBuy) {
                    //todo 购买逻辑
                } else {
                    //todo 加入购物车逻辑
                    addCart();
                }

            }
        });
    }

    //popupwindow条目点击逻辑
    private void popItemChecked(int position, List<GoodDetailBean.DataBean.SkusBean> data, int size, GoodDetailPopAdapter goodDetailPopAdapter, CircularImageView imageHead, TextView newPriceText, TextView olderPriceText) {
        if (data.get(position).getSnapupNumber() > 0) {//是活动,并且有库存
            for (int i = 0; i < size; i++) {
                data.get(i).setSelected(false);
            }
            data.get(position).setSelected(true);
            goodDetailPopAdapter.notifyDataSetChanged();
            popOtherOneItem(position, data, imageHead, newPriceText, olderPriceText);
        }
    }

    //popupwindow的显示价格和图片
    private void popOtherOneItem(int postion, List<GoodDetailBean.DataBean.SkusBean> skus, CircularImageView imageHead, TextView newPriceText, TextView olderPriceText) {
        GoodDetailBean.DataBean.SkusBean skusBean = skus.get(postion);
        String thumbImageUrl = skusBean.getThumbImageUrl();
        Glide.with(this).load(Gjmall.getOssHost() + thumbImageUrl).into(imageHead);
        if (skusBean.isWhetherActivite()) {//活动商品
            newPriceText.setText(String.format(Locale.CHINA, "¥ %s", PriceFormatUtils.valueFormatWithTwo(String.valueOf(skusBean.getSnapupPrice()))));
        } else {//非活动商品
            newPriceText.setText(String.format(Locale.CHINA, "¥ %s", PriceFormatUtils.valueFormatWithTwo(String.valueOf(skusBean.getPrice()))));
        }
        olderPriceText.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        olderPriceText.setText(String.format(Locale.CHINA, "¥ %s", PriceFormatUtils.valueFormatWithTwo(String.valueOf(skusBean.getAvecostPrice()))));
    }


    //添加购物车方式
    private void addCart() {

        JSONArray imageList = JSON.parseArray(imageUrl);
        if (bitmap == null) {
            Glide.with(this).load(Gjmall.getOssHost() + imageList.get(0)).asBitmap().override(100, 100).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    bitmap = resource;
                    measureView(imageCar, bitmap);

                }
            });
        } else {
            measureView(imageCar, bitmap);
        }
    }

    /*---------------------------------------重复代码提取----------------------------------------------*/

    //展示轮播图
    private void showBanner(GoodDetailBean.DataBean data) {
        String imageUrl = data.getImageUrl();
        JSONArray imageList = JSON.parseArray(imageUrl);
        new GoodDetailConvenientBannerHelper(this, homeBanner, imageList, false).initConvenientBanner();
    }

    //商品标题
    private void showGoodTitle(GoodDetailBean.DataBean data) {
        String title = data.getTitle();//标题
        String sellPattern = data.getSellPattern();//商品类型
        IconTextSpanUtils.setText(this, title, sellPattern, gooddetailTitle);
    }

    //显示店主挣多少钱
    private void showMakeMoney(GoodDetailBean.DataBean data) {
        if (data.getEarn() == null) {
            //todo 商品详情的赚钱,后续判断
            gooddetailZhenqian.setVisibility(View.INVISIBLE);
        } else {
            gooddetailZhenqian.setText("赚 ¥" + data.getEarn());
        }
    }

    //显示税率
    private void showSuiLv(GoodDetailBean.DataBean data) {
        if (data.getTaxes() == null) {
            //todo 商品详情页跨境税率,后续判断
            gooddetailSuilv.setVisibility(View.GONE);
        } else {
            gooddetailSuilv.setText(String.format(Locale.CHINA, "跨境综合税率约%s", data.getTaxes()));
        }
    }

    //显示是否收藏
    private void showCollect(GoodDetailBean.DataBean data) {
        if (data.getIsFavorite() == -1) {//没有收藏
            gooddetailSoucanImage.setSelected(false);
            gooddetailSoucanImage.setTag(false);

        } else {//已经收藏
            gooddetailSoucanImage.setSelected(true);
            gooddetailSoucanImage.setTag(true);
        }

    }

    //商家提示语
    private void showShopMarkedWords(GoodDetailBean.DataBean data) {
        gooddetailText1.setText(data.getDescribe());
    }

    //包邮信息
    private void showPostage(GoodDetailBean.DataBean data) {
        if (data.getIssuingBay() == 1) {//不免运费
            gooddetailText2.setText("满98元包基础运费，超重超地区运费另计");

        } else {
            gooddetailText2.setText("该商品免运费");
        }
    }

    //是否七天无理由退款
    private void showRefunded(GoodDetailBean.DataBean data) {
        if (data.isNonRefunded()) {
            gooddetailText3.setText("该商品支持七天无理由退换货政策");
        } else {
            gooddetailText3.setText("该商品不支持七天无理由退换货政策");
        }
    }

    //产品亮点
    private void showGoodStart(GoodDetailBean.DataBean data) {
        if (TextUtils.isEmpty(data.getSpecialFeature())) {
            gooddetailGoodliangdian.setVisibility(View.GONE);

        } else {
            gooddetailGoodliangdianString.setText(data.getSpecialFeature());
        }
    }

    //加载html对象
    private void showHtml(GoodDetailBean.DataBean data) {
        if (!TextUtils.isEmpty(data.getDesc())) {//webview加载html片段
            goodlistWebview.loadDataWithBaseURL(null, data.getDesc(), "text/html", "utf-8", null);

        }
    }

    //虚拟商品倒计时
    private void showVGoodCutTime(GoodDetailBean.DataBean data) {
        List<GoodDetailBean.DataBean.SkusBean> skus = data.getSkus();
        long disPlayTime = 0;
        long startTime = 0;
        long stopTime = 0;
        int size = skus.size();
        for (int i = 0; i < size; i++) {
            if (skus.get(i).isWhetherActivite()) {
                disPlayTime = skus.get(i).getGmtDisplay();
                startTime = skus.get(i).getGmtStart();
                stopTime = skus.get(i).getGmtStop();
                break;
            }
        }
        long currentTime = System.currentTimeMillis();
        if (currentTime > disPlayTime && currentTime < stopTime) {//当前时间大于可以开始显示时间.并且活动没结束
            gooddetailCutTime.setVisibility(View.VISIBLE);
            gooddetailCutTime.setTimeState(new TimeState() {
                @Override
                public void onCountdown() {
                    //todo 时间到的时候处理
                }
            });
            if (currentTime < startTime) {//预热倒计时
                gooddetailCutTime.setTvState("后开始抢购");
                gooddetailCutTime.addTime((int) ((startTime - currentTime) / 1000));
                gooddetailCutTime.start();
            } else if (currentTime > startTime) {//抢购中
                gooddetailCutTime.setTvState("后抢购结束");
                gooddetailCutTime.addTime((int) ((stopTime - currentTime) / 1000));
                gooddetailCutTime.start();
            }


        }
    }

    //实体商品倒计时
    private void showMGoodCutTime(GoodDetailBean.DataBean data) {
        List<GoodDetailBean.DataBean.SkusBean> skus = data.getSkus();
        long disPlayTime = 0;
        long startTime = 0;
        long stopTime = 0;
        int size = skus.size();
        for (int i = 0; i < size; i++) {
            if (skus.get(i).isWhetherActivite()) {
                disPlayTime = skus.get(i).getGmtDisplay();
                startTime = skus.get(i).getGmtStart();
                stopTime = skus.get(i).getGmtStop();
                break;
            }
        }
        long currentTime = System.currentTimeMillis();
        if (currentTime > disPlayTime && currentTime < stopTime) {//当前时间大于可以开始显示时间.并且活动没结束
            gooddetailCutTime.setVisibility(View.VISIBLE);
            gooddetailCutTime.setTimeState(new TimeState() {
                @Override
                public void onCountdown() {
                    //todo 时间到的时候处理
                }
            });
            if (currentTime < startTime) {//预热倒计时
                gooddetailCutTime.setTvState("后活动开始");
                gooddetailCutTime.addTime((int) ((startTime - currentTime) / 1000));
                gooddetailCutTime.start();
            } else if (currentTime > startTime) {//抢购中
                gooddetailCutTime.setTvState("后活动结束");
                gooddetailCutTime.addTime((int) ((stopTime - currentTime) / 1000));
                gooddetailCutTime.start();
            }

        }
    }

    //初始化监听事件
    private void initListener() {
        gooddetailSoucanImage.setOnClickListener(listener);//收藏的点击事件
        gooddetailGohome.setOnClickListener(listener);//前往首页
        gooddetailShare.setOnClickListener(listener);//分享按钮
        gooddetailGocar.setOnClickListener(listener);//前往购物车
    }

    /*---------------------------------------贝塞尔曲线---------------------------------------------*/
    private void measureView(ImageView iv, Bitmap resource) {
        //      一、创造出执行动画的主题---imageview
        //代码new一个imageview，图片资源是上面的imageview的图片
        // (这个图片就是执行动画的图片，从开始位置出发，经过一个抛物线（贝塞尔曲线），移动到购物车里)
        final CircularImageView goods = new CircularImageView(GoodDetailActivity.this);
        goods.setImageBitmap(resource);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
        gooddetailRl.addView(goods, params);

//        二、计算动画开始/结束点的坐标的准备工作
        //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        int[] parentLocation = new int[2];
        gooddetailRl.getLocationInWindow(parentLocation);

        //得到商品图片的坐标（用于计算动画开始的坐标）
        int startLoc[] = new int[2];
        iv.getLocationInWindow(startLoc);

        //得到购物车图片的坐标(用于计算动画结束后的坐标)
        int endLoc[] = new int[2];
        gooddetailGocar.getLocationInWindow(endLoc);


//        三、正式开始计算动画开始/结束的坐标
        //开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
        float startX = startLoc[0] - parentLocation[0] + iv.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + iv.getHeight() / 2;

        //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
        float toX = endLoc[0] - parentLocation[0] + gooddetailnomalbuttomAddcar.getWidth() / 5;
        float toY = endLoc[1] - parentLocation[1];

//        四、计算中间动画的插值坐标（贝塞尔曲线）（其实就是用贝塞尔曲线来完成起终点的过程）
        //开始绘制贝塞尔曲线
        Path path = new Path();
        //移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY);
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        //mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，
        // 如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        //★★★属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);
        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // ★★★★★获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
                // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                mPathMeasure.getPosTan(value, mCurrentPosition, null);//mCurrentPosition此时就是中间距离点的坐标值
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });
//      五、 开始执行动画
        valueAnimator.start();

//      六、动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            //当动画结束后：
            @Override
            public void onAnimationEnd(Animator animation) {
              /*  // 购物车的数量加1
                i++;
                count.setText(String.valueOf(i));
                // 把移动的图片imageview从父布局里移除
                */
                carNum++;
                unreadNum.setVisibility(View.VISIBLE);
                unreadNum.setText(String.valueOf(carNum));
                gooddetailRl.removeView(goods);//把imageview移除
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }


}
